import datetime
import json
import logging

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from web import models

logger = logging.getLogger(__name__)

# In your code

logger.debug('Some message')  # Logs as debug message
logger.error('Error message')  # Logs as error message


@csrf_exempt
def api(request):
    risk_mapping = {'低风险': 'inject_low_count', '中风险': 'inject_middle_count', '高风险': 'inject_high_count'}
    if request.method == 'GET':
        return JsonResponse({'success': True})
    if request.method == 'POST':
        data_list = [item.name for item in models.Botgate._meta.get_fields()]
        result = json.loads(request.body.decode('utf-8'))
        if result.get('date') == 'current_day':
            current_time = datetime.datetime.now()
        else:
            current_time = datetime.datetime.now() + datetime.timedelta(days=1)
        if len(result['mobiledj']) > 0:
            collect_time_str = result['mobiledj'][0].get('current_time', '')
            if collect_time_str:
                obj = models.Botgate.objects.filter(create_datetime__year=current_time.year,
                                                    create_datetime__month=current_time.month,
                                                    create_datetime__day=current_time.day)
                if obj:
                    for key, value in result['mobiledj'][0].items():
                        if key in data_list:
                            data = {key: value}
                            # data['create_datetime'] = current_time
                            obj.update(**data)
                else:
                    for key, value in result['mobiledj'][0].items():
                        if key in data_list:
                            data = {key: value}
                            data['create_datetime'] = current_time
                            models.Botgate.objects.create(**data)
            else:
                if result['mobiledj'][0].get('risk_level', ''):
                    obj = models.Botgate.objects.filter(create_datetime__year=current_time.year,
                                                        create_datetime__month=current_time.month,
                                                        create_datetime__day=current_time.day).first()
                    for data in result['mobiledj']:
                        if obj:
                            field_name = risk_mapping[data.get('risk_level')]
                            setattr(obj, field_name, data.get('inject_level_count'))
                            obj.save()
                        else:
                            data_dict = {risk_mapping[data.get('risk_level')]: data.get('inject_level_count')}
                            data['create_datetime'] = current_time
                            models.Botgate.objects.create(**data_dict)
                elif result['mobiledj'][0].get('warning_level'):
                    obj = models.Botgate.objects.filter(create_datetime__year=current_time.year,
                                                        create_datetime__month=current_time.month,
                                                        create_datetime__day=current_time.day).first()
                    field_mapping = {'低风险': 'low_warning_count',
                                     '中风险': 'middle_warning_count',
                                     '高风险': 'high_warning_count'}
                    for data in result['mobiledj']:
                        if obj:
                            field_name = field_mapping[data.get('warning_level')]
                            setattr(obj, field_name, data.get('warning_count'))
                            obj.save()
                        else:
                            data_dict = {field_mapping[data.get('warning_level')]: data.get('warning_count')}
                            data['create_datetime'] = current_time
                            models.Botgate.objects.create(**data_dict)
    return JsonResponse({'success': True})


@csrf_exempt
def api_v2(request):
    if request.method == 'GET':
        return JsonResponse({'success': True})
    if request.method == 'POST':
        result = json.loads(request.body.decode('utf-8'))
        if result.get('date') == 'current_day':
            current_time = datetime.datetime.now()
        else:
            current_time = datetime.datetime.now() + datetime.timedelta(days=1)
        if len(result['mobiledj']) > 0:
            if result['mobiledj'][0].get('warning'):
                risk_mapping = {
                    '高风险': '1',
                    '中风险': '2',
                    '低风险': '3'
                }
                for data in result['mobiledj']:
                    data_dict = {}
                    for key, value in data.items():
                        if key == 'risk_level':
                            data_dict[key] = risk_mapping[value]
                        else:
                            data_dict[key] = value
                    obj = models.BotgateWarnLog.objects.filter(
                        warning=data_dict['warning'],
                        risk_level=data_dict['risk_level'],
                        create_datetime__year=current_time.year,
                        create_datetime__month=current_time.month,
                        create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateWarnLog.objects.create(**data_dict)
            elif result['mobiledj'][0].get('nday_list'):
                for data in result['mobiledj']:
                    data_dict = data
                    data_dict.pop('nday_list')
                    obj = models.BotgateAttackIp.objects.filter(src_ip=data['src_ip'],
                                                                create_datetime__year=current_time.year,
                                                                create_datetime__month=current_time.month,
                                                                create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateAttackIp.objects.create(**data_dict)
            elif result['mobiledj'][0].get('risk_level'):
                risk_mapping = {
                    '高风险': 'high_risk_count',
                    '中风险': 'middle_risk_count',
                    '低风险': 'low_risk_count'
                }
                for data in result['mobiledj']:
                    data_dict = {}
                    for key, value in data.items():
                        if key == 'risk_level':
                            try:
                                data_dict[risk_mapping[value]] = data['warning_count']
                            except Exception as e:
                                continue
                        elif key == 'warning_count':
                            continue
                        else:
                            data_dict[key] = value
                    obj = models.BotgateAttackIp.objects.filter(src_ip=data['src_ip'],
                                                                create_datetime__year=current_time.year,
                                                                create_datetime__month=current_time.month,
                                                                create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
            elif result['mobiledj'][0].get('attack'):
                field_mapping = {
                    '简单脚本攻击': 'no_cookie_count',
                    '漏洞攻击': 'inject_attack_count',
                    '高级自动化工具': 'bot_attack_count',
                    '重放攻击': 'replay_attack_count'
                }
                for data in result['mobiledj']:
                    data_dict = {}
                    for key, value in data.items():
                        if key == 'attack':
                            try:
                                data_dict[field_mapping[value]] = data['attack_count']
                            except Exception as e:
                                continue
                        elif key == 'attack_count':
                            continue
                        else:
                            data_dict[key] = value

                    obj = models.BotgateAttackIp.objects.filter(src_ip=data['src_ip'],
                                                                create_datetime__year=current_time.year,
                                                                create_datetime__month=current_time.month,
                                                                create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                        # for item in obj:
                        #     logger.info("%s,%s,%s" % (data_dict, item.create_datetime, item.update_datetime))
            elif result['mobiledj'][0].get('src_ip'):
                for data in result['mobiledj']:
                    data_dict = {key: value for key, value in data.items()}
                    obj = models.BotgateAttackIp.objects.filter(src_ip=data['src_ip'],
                                                                create_datetime__year=current_time.year,
                                                                create_datetime__month=current_time.month,
                                                                create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                        # for item in obj:
                        #     logger.info("%s,%s,%s" % (data_dict, item.create_datetime, item.update_datetime))
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateAttackIp.objects.create(**data_dict)
            elif result['mobiledj'][0].get('inject_attack_type'):
                for data in result['mobiledj']:
                    data_dict = {'attack_type' if key == 'inject_attack_type' else key: value for key, value in
                                 data.items()}

                    obj = models.BotgateInjectAttackType.objects.filter(attack_type=data['inject_attack_type'],
                                                                        create_datetime__year=current_time.year,
                                                                        create_datetime__month=current_time.month,
                                                                        create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)

                        # for item in obj:
                        #     logger.info("%s,%s,%s" % (data_dict, item.create_datetime, item.update_datetime))
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateInjectAttackType.objects.create(**data_dict)
            elif result['mobiledj'][0].get('path'):
                for data in result['mobiledj']:
                    data_dict = {key: value for key, value in data.items()}

                    obj = models.BotgateAttackPath.objects.filter(path=data['path'],
                                                                  create_datetime__year=current_time.year,
                                                                  create_datetime__month=current_time.month,
                                                                  create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                        # for item in obj:
                        #     logger.info("%s,%s,%s" % (data_dict, item.create_datetime, item.update_datetime))
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateAttackPath.objects.create(**data_dict)
            elif result['mobiledj'][0].get('attack_type'):
                for data in result['mobiledj']:
                    data_dict = {key: value for key, value in data.items()}

                    obj = models.BotgateAttackType.objects.filter(attack_type=data['attack_type'],
                                                                  create_datetime__year=current_time.year,
                                                                  create_datetime__month=current_time.month,
                                                                  create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                        # for item in obj:
                        #     logger.info("%s,%s,%s" % (data_dict, item.create_datetime, item.update_datetime))
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateAttackType.objects.create(**data_dict)
            elif result['mobiledj'][0].get('website'):
                for data in result['mobiledj']:
                    data_dict = {}
                    for key, value in data.items():
                        if key == 'normal_count':
                            data_dict['request_type'] = 1
                            data_dict['request_count'] = value
                        elif key == 'abnormal_count':
                            data_dict['request_type'] = 2
                            data_dict['request_count'] = value
                        else:
                            data_dict[key] = value
                    obj = models.BotgateWebSiteRequest.objects.filter(website=data['website'],
                                                                      request_type=data_dict['request_type'],
                                                                      create_datetime__year=current_time.year,
                                                                      create_datetime__month=current_time.month,
                                                                      create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateWebSiteRequest.objects.create(**data_dict)
            elif result['mobiledj'][0].get('website_bandwidth'):
                for data in result['mobiledj']:
                    data_dict = {}
                    obj = models.BotgateWebSiteRequest.objects.filter(website=data['website_bandwidth'],
                                                                      request_type=1,
                                                                      create_datetime__year=current_time.year,
                                                                      create_datetime__month=current_time.month,
                                                                      create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        data_dict['bandwidth'] = data['bandwidth']
                        obj.update(**data_dict)
            elif result['mobiledj'][0].get('nday'):
                for data in result['mobiledj']:
                    data_dict = {}
                    for key, value in data.items():
                        if key == 'nday':
                            data_dict['nday_name'] = value
                        elif key == 'nday_count':
                            data_dict['nday_attack_count'] = value
                    obj = models.BotgateNdayType.objects.filter(nday_name=data['nday'],
                                                                create_datetime__year=current_time.year,
                                                                create_datetime__month=current_time.month,
                                                                create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateNdayType.objects.create(**data_dict)
            elif result['mobiledj'][0].get('bot_type'):
                for data in result['mobiledj']:
                    data_dict = {key: value for key, value in data.items()}
                    obj = models.BotgateBotType.objects.filter(bot_type=data['bot_type'],
                                                               create_datetime__year=current_time.year,
                                                               create_datetime__month=current_time.month,
                                                               create_datetime__day=current_time.day)
                    if obj:
                        data_dict['update_datetime'] = datetime.datetime.now()
                        obj.update(**data_dict)
                    else:
                        data_dict['create_datetime'] = current_time
                        models.BotgateBotType.objects.create(**data_dict)

    return JsonResponse({'success': True})
